package com.upload;

import com.utils.StreamUtils;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * 1. 文件上传的客户端
 */
public class TcpFileUploadClient {
    public static void main(String[] args) throws IOException {
        // 1. 链接到服务器端
        System.out.println("InetAddress.getLocalHost() = " + InetAddress.getLocalHost());
        Socket socket = new Socket(InetAddress.getLocalHost(), 8888);
        System.out.println("服务器链接成功.......");

        // 2. 创建读取磁盘文件的输入流
        String path="e:\\qie.png";
        // 读取磁盘文件的输入流
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(path));
        // 将文件读取到一个字节数组中
        byte[] bytes = StreamUtils.streamToByteArray(bis);

        // 3.将文件内容，通过 socket发送到服务器端
        OutputStream outputStream = socket.getOutputStream(); // 输出流
        BufferedOutputStream bos = new BufferedOutputStream(outputStream);
        bos.write(bytes); // 将文件对应的字节数组，写入到 socket的数据通道中
        bis.close();
        socket.shutdownOutput();// 设置写入数据的结束标记


        // 从socket中读取服务器端发送的数据
        // 接受从服务器端回送的消息
        InputStream inputStream = socket.getInputStream();
        String s = StreamUtils.streamToString(inputStream);
        System.out.println(s);

        // 4.关闭相关流
        inputStream.close();
        bos.close();
        socket.close();

    }
}
